package com.cy.stone.framework.systemdict;

import com.cy.stone.common.constant.Constant;
import com.cy.stone.common.utils.StringUtils;
import com.cy.stone.system.infrastructure.database.entity.DictDataEntity;
import com.cy.stone.system.infrastructure.database.service.IDictDataService;
import com.houkunlin.system.dict.starter.bean.DictTypeVo;
import com.houkunlin.system.dict.starter.notice.RefreshDictEvent;
import com.houkunlin.system.dict.starter.store.RemoteDict;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

import static com.cy.stone.system.infrastructure.database.table.DictDataTableDef.DICT_DATA_ENTITY;

/**
 * 当缓存中获取不到时，从这获取
 * @author Wings
 * @since 2023-12-17
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class StoneRemoteDict implements RemoteDict {

    private final IDictDataService dictDataService;

    @Override
    public DictTypeVo getDictType(String type) {
        // 从其他地方（其他服务、数据库、本地文件）加载一个完整的数据字典信息（字典类型+字典值列表）
        List<DictDataEntity> dicts = dictDataService.list(QueryWrapper.create()
                .from(DICT_DATA_ENTITY)
                .where(DICT_DATA_ENTITY.DICT_TYPE.eq(type))
                .and(DICT_DATA_ENTITY.STATUS.eq(Constant.STATUS_0)));
        DictTypeVo.DictTypeBuilder builder = DictTypeVo.newBuilder(type, type);
        for(DictDataEntity dict : dicts) {
            builder.add(dict.getDictCode(), dict.getDictValue());
        }
        return builder.build();
    }

    @Override
    public String getDictText(String type, String value) {
        Optional<DictDataEntity> dictDataOptional = dictDataService.getOneOpt(QueryWrapper.create()
                .from(DICT_DATA_ENTITY)
                .where(DICT_DATA_ENTITY.DICT_TYPE.eq(type))
                .and(DICT_DATA_ENTITY.DICT_VALUE.eq(value))
                .and(DICT_DATA_ENTITY.STATUS.eq(Constant.STATUS_0)));
        if (dictDataOptional.isPresent()) {
            return dictDataOptional.get().getDictValue();
        } else {
            return StringUtils.EMPTY;
        }
    }
}
